import axios from "axios"
import { MessageBox, Message } from "element-ui"
import store from "@/store"
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from "@/utils/auth"

NProgress.configure({ showSpinner: false }) // NProgress Configuration

// create an axios instance
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 5000
})
const TOKEN_HEADER = "Authorization";
const TOKEN_PREFIX = "Bearer ";

// request interceptor
service.interceptors.request.use(
  config => {
    const token = getToken()
    token && (config.headers[TOKEN_HEADER] = TOKEN_PREFIX + token)
    NProgress.start()
    return config
  },
  error => {
    NProgress.done()
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    NProgress.done()
    const res = response.data
    // if the custom code is not 20000, it is judged as an error.
    if (res.code !== 200) {
      Message({
        message: res.message || res.msg || "Error",
        type: "error",
        duration: 5 * 1000
      })

      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      const errCodes = [50008, 50012, 50014]
      if (errCodes.contains(res.code)) {
        // to re-login
        MessageBox.confirm(
          "登录已过期，请重新登录！",
          "消息提示",
          {
            confirmButtonText: "确认",
            cancelButtonText: "取消",
            type: "warning"
          }
        ).then(() => {
          store.dispatch("user/resetToken").then(() => {
            location.reload()
          })
        })
      }
      return Promise.reject(new Error(res.message || "Error"))
    }
    return res
  },
  error => {
    NProgress.done()
    console.log("========请求错误=========")
    console.error(error);
    console.log("========请求错误=========")

    let message = error.response.data?.msg || "未知错误"
    Message({
      message,
      type: "error",
      duration: 3 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
